<script>
import { onMounted, onBeforeUnmount, reactive, toRefs, ref } from "vue";

import * as echarts from "echarts";
export default {
  props: {
    title: { type: String, default: "" }, //标题
    labelList: { type: Array, default: [] }, //标签列表
    dataList: { type: Array, default: [] }, //数据列表
  },
  setup(props) {
    const state = reactive({});

    const echartContainer = ref();
    let myChart = null;

    const resizeHandler = () => {
      myChart.resize();
    };

    //防抖
    const debounce = (func, wait) => {
      let timeout;
      return function () {
        const context = this;
        const args = arguments;
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(() => {
          func.apply(context, args);
        }, wait);
      };
    };

    const cancalDebounce = debounce(resizeHandler, 500);

    const initChart = () => {
      myChart = echarts.init(echartContainer.value);

      window.addEventListener("resize", cancalDebounce);

      let option = {
        xAxis: {
          type: "value",
        },
        yAxis: {
          type: "category",
          data: props.labelList,
        },
        series: [
          {
            data: props.dataList,
            type: "bar",
          },
        ],
      };

      myChart.setOption(option);
    };

    onMounted(() => {
      initChart();
    });

    onBeforeUnmount(() => {
      window.removeEventListener("resize", cancalDebounce);
      myChart.dispose();
    });

    return { ...toRefs(state), echartContainer };
  },
};
</script>

<template>
  <el-card shadow="never" style="width: 100%; height: 100%">
    <template #header> {{ title }}</template>
    <div ref="echartContainer" style="width: 100%; height: 100%"></div>
  </el-card>
</template>
<style scoped>
</style>